#include "include/widgets/main_window.hpp"
#include <QDateTime>
#include <QMessageBox>
#include <QTimer>

MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) {
  // 初始化交易系统
  m_tradingSystem = new TradingSystem(this);
  if (!m_tradingSystem->initialize()) {
    QMessageBox::critical(this, "错误", "初始化交易系统失败");
    exit(1);
  }

  setupUI();
  setupMenuBar();
  setupStatusBar();
  setupConnections();

  setWindowTitle("股票模拟交易系统 Create By:LCM");
  setMinimumSize(1800, 1200);

  // 如果没有登录，则弹出登录对话框
  if (!m_tradingSystem->isLoggedIn()) {
    QTimer::singleShot(100, this, &MainWindow::onLogin);
  }
}

MainWindow::~MainWindow() {
  // 保存用户数据
  if (m_tradingSystem) {
    m_tradingSystem->saveUserData();
  }
}

void MainWindow::setupUI() {
  // 创建标签页部件
  m_tabWidget = new QTabWidget(this);

  // 创建各个标签页内容
  m_stockInfoWidget =
      new StockInfoWidget(m_tradingSystem->getMarketDataManager(), this);
  m_tradingWidget = new TradingWidget(m_tradingSystem, this);
  m_portfolioWidget = new PortfolioWidget(m_tradingSystem, this);
  m_reportWidget = new ReportWidget(m_tradingSystem, this);

  // 添加标签页
  m_tabWidget->addTab(m_stockInfoWidget, "股票行情");
  m_tabWidget->addTab(m_tradingWidget, "交易");
  m_tabWidget->addTab(m_portfolioWidget, "投资组合");
  m_tabWidget->addTab(m_reportWidget, "交易记录");

  // 设置中央部件
  setCentralWidget(m_tabWidget);
}

void MainWindow::setupMenuBar() {
  // 创建文件菜单
  QMenu *fileMenu = menuBar()->addMenu("文件");

  // 登录和登出操作
  m_loginAction = fileMenu->addAction("登录");
  m_logoutAction = fileMenu->addAction("登出");
  m_logoutAction->setEnabled(false);

  fileMenu->addSeparator();

  // 退出操作
  QAction *exitAction = fileMenu->addAction("退出");
  connect(exitAction, &QAction::triggered, this, &QMainWindow::close);

  // 创建帮助菜单
  QMenu *helpMenu = menuBar()->addMenu("帮助");

  // 关于操作
  QAction *aboutAction = helpMenu->addAction("关于");
  QAction *emailAction = helpMenu->addAction("联系我们");

  connect(aboutAction, &QAction::triggered, [this]() {
    QMessageBox::about(this, "关于",
                       "股票模拟交易系统\n"
                       "版本：1.3\n"
                       "Maintained By: LiChunMei\n"
                       "© 2023 股票模拟交易系统项目组");
  });
  connect(emailAction, &QAction::triggered, [this]() {
    QMessageBox::information(this, "联系我们",
                             "如有任何问题，请联系：\n"
                             "Email:3323724634@qq.com");
  });
}

void MainWindow::setupStatusBar() {
  m_statusLabel = new QLabel("未登录", this);
  statusBar()->addWidget(m_statusLabel);

  m_timeLabel = new QLabel(this);
  statusBar()->addPermanentWidget(m_timeLabel);

  // 定时更新时间
  QTimer *timer = new QTimer(this);
  connect(timer, &QTimer::timeout, this, &MainWindow::updateStatusBar);
  timer->start(1000);
  updateStatusBar();
}

void MainWindow::setupConnections() {
  // 登录登出操作
  connect(m_loginAction, &QAction::triggered, this, &MainWindow::onLogin);
  connect(m_logoutAction, &QAction::triggered, this, &MainWindow::onLogout);

  // 交易系统信号
  connect(m_tradingSystem, &TradingSystem::userLoggedIn, this,
          &MainWindow::onUserLoggedIn);
  connect(m_tradingSystem, &TradingSystem::userLoggedOut, this,
          &MainWindow::onUserLoggedOut);

  // 股票选择信号
  connect(m_stockInfoWidget, &StockInfoWidget::stockSelected, this,
          &MainWindow::onStockSelected);
  connect(m_portfolioWidget, &PortfolioWidget::stockSelected, this,
          &MainWindow::onStockSelected);
}

void MainWindow::onLogin() {
  LoginDialog loginDialog(m_tradingSystem, this);
  loginDialog.exec();
}

void MainWindow::onLogout() {
  if (QMessageBox::question(this, "确认", "确定要登出当前用户吗？") ==
      QMessageBox::Yes) {
    m_tradingSystem->logoutUser();
  }
}

void MainWindow::onUserLoggedIn(const QString &username) {
  m_loginAction->setEnabled(false);
  m_logoutAction->setEnabled(true);
  m_statusLabel->setText(QString("当前用户：%1").arg(username));

  // 刷新持仓和交易记录
  m_portfolioWidget->onAccountUpdated();
  m_reportWidget->refreshTransactionTable();
}

void MainWindow::onUserLoggedOut() {
  m_loginAction->setEnabled(true);
  m_logoutAction->setEnabled(false);
  m_statusLabel->setText("未登录");

  // 弹出登录对话框
  QTimer::singleShot(100, this, &MainWindow::onLogin);
}

void MainWindow::updateStatusBar() {
  QDateTime currentTime = QDateTime::currentDateTime();
  m_timeLabel->setText(currentTime.toString("yyyy-MM-dd hh:mm:ss"));
}

void MainWindow::onStockSelected(const QString &stockCode,
                                 const QString &stockName, double price) {
  m_tradingWidget->onStockSelected(stockCode, stockName, price);

  // 切换到交易标签页
  m_tabWidget->setCurrentIndex(1);
}
